<template>
  <div class="container">
    <div class="investment_projects">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="search">
          <a-form-item label="投资项目名称">
            <a-input v-model="queryParam.projectName" placeholder="请输入投资项目名称" />
          </a-form-item>
          <a-form-item label="投资类型">
            <a-select v-model="queryParam.investmentType" placeholder="请选择投资类型" style="width: 200px">
              <a-select-option :key="item.key" v-for="item in option" @onchange="onchange(item, 0)">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="认购类型">
            <a-select v-model="queryParam.subscriptionType" placeholder="请选择认购类型" style="width: 200px">
              <a-select-option :key="item.key" v-for="item in option1" @onchange="onchange(item, 1)">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" htmlType="submit" @click="search">查询</a-button>
            <a-button htmlType="submit" class="ml15" @click="searchReset">重置</a-button>
            <a-button htmlType="submit" type="primary" class="ml15" @click="addAndEdit('add')">+添加新投资</a-button>
          </a-form-item>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        :columns="columns"
        :data="loadData"
        bordered
        :rowKey="(record) => record.id"
      >
      <span slot="isOpen" slot-scope="text, record">
        <a-switch :defaultChecked="text === 1 ? true : false" @change="switchOnChange(record)" />
      </span>
      <template slot="action" slot-scope="text, record">
        <a-button size="small" type="primary" @click="addAndEdit('edit', record)">编辑</a-button>
        <a-button size="small" type="dashed" class="ml15" @click="viewModal(record)">查看详情</a-button>
      </template>
      </s-table>
      <a-modal :title="title" v-model="visible" @ok="handleOk" class="modal">
        <a-form :form="form" class="permission-form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="投资名称">
            <a-input
              v-decorator="[
              'projectName',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入投资名称!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.projectName,
              },
            ]"
              placeholder="请输入投资名称"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="投资类型">
            <a-input
              v-decorator="[
              'investmentType',
              {
                rules: [
                  {
                    required: true,
                    message: '请选择投资类型!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.investmentType,
              },
            ]"
              placeholder="请选择投资类型"
              options="option"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="认购类型">
            <a-input
              v-decorator="[
              'subscriptionType',
              {
                rules: [
                  {
                    required: true,
                    message: '请选择认购类型!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.subscriptionType,
              },
            ]"
              placeholder="请选择认购类型"
              options="option1"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="认购周期">
            <a-input
              v-decorator="[
              'subscriptionCycle',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入认购周期!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.subscriptionCycle,
              },
            ]"
              placeholder="请输入认购周期"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单笔最小数">
            <a-input
              v-decorator="[
              'startFunds',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入单笔最小数!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.startFunds,
              },
            ]"
              placeholder="请输入单笔最小数"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="返回方式（文案）">
            <a-input
              v-decorator="[
              'returnMethod',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入返回方式（文案）!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.returnMethod,
              },
            ]"
              placeholder="请输入返回方式（文案）"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="标签名称（文案）">
            <a-input
              v-decorator="[
              'tagName',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入标签名称（文案）!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.tagName,
              },
            ]"
              placeholder="请输入标签名称（文案）"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="限投次数">
            <a-input
              v-decorator="[
              'purchaseLimit',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入限投次数!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.purchaseLimit,
              },
            ]"
              placeholder="请输入限投次数"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="会员等级">
            <a-input
              v-decorator="[
              'memberLevel',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入会员等级!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.memberLevel,
              },
            ]"
              placeholder="请输入会员等级"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="高级合伙人等级">
            <a-input
              v-decorator="[
              'seniorPartnerLevel',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入高级合伙人等级!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.seniorPartnerLevel,
              },
            ]"
              placeholder="请输入高级合伙人等级"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="项目最大数">
            <a-input
              v-decorator="[
              'projectMaxFunds',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入项目最大数!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.projectMaxFunds,
              },
            ]"
              placeholder="请输入项目最大数"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="单笔最大数">
            <a-input
              v-decorator="[
              'maxSubscription',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入单笔最大数!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.maxSubscription,
              },
            ]"
              placeholder="请输入单笔最大数"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收益率（%）">
            <a-input
              v-decorator="[
              'incomeRate',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入收益率（%）!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.incomeRate,
              },
            ]"
              placeholder="请输入收益率（%）"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="结算时间（文案）">
            <a-textarea
              v-decorator="[
              'settlementTime',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入结算时间（文案）内容!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.settlementTime,
              },
            ]"
              placeholder="请输入结算时间（文案）内容"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收益计算（文案）">
            <a-textarea
              v-decorator="[
              'revenueCalculation',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入收益计算（文案）内容!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.revenueCalculation,
              },
            ]"
              placeholder="请输入收益计算（文案）内容"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="可认购金额（文案）">
            <a-textarea
              v-decorator="[
              'individualSubscriptionAmount',
              {
                rules: [
                  {
                    required: true,
                    message: '可认购金额（文案）!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.individualSubscriptionAmount,
              },
            ]"
              placeholder="请输入可认购金额（文案）内容"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-item>
          <a-form-item label="项目图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <image-upload
              v-decorator="[
              'projectImgList',
              {
                rules: [
                  {
                    required: true,
                    message: '请上传项目图片!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.projectImgList,
              },
            ]"
              :value="info.projectImgList ?? []"
              :action="action"
              :multiple="false"
              :number="1"
              :idStr="info.projectImg ?? ''"
            >
            </image-upload>
          </a-form-item>
          <a-form-item label="委托协议" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <image-upload
              v-decorator="[
              'trustAgreementImgList',
              {
                rules: [
                  {
                    required: true,
                    message: '请上传委托协议!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.trustAgreementImgList,
              },
            ]"
              :multiple="true"
              :value="info.trustAgreementImgList ?? []"
              :idStr="info.trustAgreement ?? ''"
              :action="action"
              :number="20"
            >
            </image-upload>
          </a-form-item>
          <a-form-item label="项目详情" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <image-upload
              v-decorator="[
              'projectDetailsImgList',
              {
                rules: [
                  {
                    required: true,
                    message: '请上传项目详情!',
                  },
                ],
                initialValue: title === '添加新投资' ? '' : info.projectDetailsImgList,
              },
            ]"
              :value="info.projectDetailsImgList ?? []"
              :action="action"
              :number="20"
              :idStr="info.projectDetails ?? ''"
            >
              <div v-if="fileList?.length < 2">
                <a-icon type="plus" />
                <div class="ant-upload-text">添加</div>
              </div>
            </image-upload>
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
      <a-modal title="查看详情" v-model="visible1">
        <template #footer>
          <a-button type="primary" @click="visible1 = false"> 关闭 </a-button>
        </template>
        <div class="user_info">
          <div class="item">
            <div>
              <span>已投资金额：</span><span>{{ common.numFormat(detailInfo?.investmentAmountSuccess ?? 0) }}</span>
            </div>
          </div>
          <div class="item">
            <div>
              <span>认购人数：</span><span>{{ common.numFormat(detailInfo?.memberCount ?? 0) }}</span>
            </div>
          </div>
          <div class="item">
            <div>
              <span>认购笔数：</span><span>{{ common.numFormat(detailInfo?.subscriptionCount ?? 0) }}</span>
            </div>
          </div>
          <div class="item">
            <div>
              <span>结算利息：</span><span>{{ common.numFormat(detailInfo?.settlementAmountCount ?? 0) }}</span>
            </div>
          </div>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import STable from '@/components/Table'
import ImageUpload from '@/components/ImageUpload'
import {
  investorsList,
  investorsListAdd,
  investorsListUpdateById,
  investorsListUpdateStatusById,
  investorsListDetail,
  investorsListGetById,
  // commonUploadImg,
} from '@/api/configuration-management'
import { common } from '@/common/index'
import { mapGetters } from 'vuex'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default {
  name: 'investmentProjects',
  components: {
    STable,
    ImageUpload,
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  data() {
    return {
      form: this.$form.createForm(this),
      action: '/vietnam-travel-admin/configurationManagement/v1/upload-file',
      formLayout: 'horizontal',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      option: [
        { label: 'BIỂN ĐẢO', value: 1, key: 1 },
        { label: 'DU LỊCH', value: 2, key: 2 },
        { label: 'VY-TRAVEL', value: 3, key: 3 },
      ],
      option1: [
        { label: '小时', value: 1, key: 1 },
        { label: '天数', value: 2, key: 2 },
        { label: '单月', value: 3, key: 3 },
      ],
      visible: false,
      visible1: false,
      title: '',
      info: {},
      detailInfo: {},
      previewVisible: false,
      previewImage: '',
      columns: [
        {
          title: 'ID',
          dataIndex: 'id',
          align: 'center'
        },
        {
          title: '投资类型',
          dataIndex: 'investmentType',
          align: 'center'
        },
        {
          title: '投资项目名称',
          dataIndex: 'projectName',
          customRender: (text) => (text ? text : '-'),
          align: 'center'
        },
        {
          title: '认购类型',
          dataIndex: 'subscriptionType',
          align: 'center'
        },
        {
          title: '认购周期',
          dataIndex: 'subscriptionCycle',
          align: 'center'
        },
        {
          title: '起购金额',
          dataIndex: 'startFunds',
          customRender: (text) => this.common.numFormat(text),
          align: 'center'
        },
        {
          title: '已投资金额数',
          dataIndex: 'investmentAmountSuccess',
          customRender: (text) => this.common.numFormat(text),
          align: 'center'
        },
        {
          title: '活动状态',
          dataIndex: 'isOpen',
          slots: { title: 'isOpen' },
          scopedSlots: { customRender: 'isOpen' },
          align: 'center'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          slots: { title: 'action' },
          scopedSlots: { customRender: 'action' },
          align: 'center'
        },
      ],
      // 查询条件参数
      queryParam: { projectName: '', investmentType: '', subscriptionType: '' },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const { userId } = this.userInfo

        let params = {
          // ...parameter,
          userId,
          page: parameter.pageNum,
          pageSize: parameter.pageSize,
          ...this.queryParam,
        }
        return new Promise((resolve, reject) => {
          investorsList(params)
            .then((res) => {
              if (res.code === 200) {
                resolve(res.data)
              } else {
                this.$message.error(res?.msg)
              }
            })
            .catch((err) => {
              reject(err)
            })
            .finally(() => {})
        })
      },
    }
  },
  methods: {
    switchOnChange(record) {
      investorsListUpdateStatusById({
        isOpen: !record.isOpen === true ? 1 : 0,
        id: record.id,
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
        this.$refs.table.refresh()
      })
    },
    addAndEdit(type, record = {}) {
      if (type === 'edit') {
        const { userId } = this.userInfo
        const params = {
          id: record.id,
          userId,
        }
        investorsListGetById(params).then((res) => {
          if (res.code === 200) {
            this.info = res.data ?? {}
          }
        })
      } else {
        this.info = {}
        this.form.resetFields()
      }
      this.title = type === 'edit' ? '编辑投资' : '添加新投资'
      this.visible = true
    },
    refresh(isBackToFirstPage = false) {
      this.$refs.table.refresh(isBackToFirstPage)
    },
    search() {
      this.refresh(false)
    },
    searchReset() {
      this.queryParam = { projectName: '', investmentType: '', subscriptionType: '' }
      this.refresh(true)
    },

    viewModal(record) {
      this.visible1 = true
      const { userId } = this.userInfo
      const params = {
        id: record.id,
        isOpen: record.isOpen,
        userId,
      }
      investorsListDetail(params).then((res) => {
        if (res.code === 200) {
          this.detailInfo = res.data ?? {}
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const { userId } = this.userInfo
          let params = {
            id: this.info.id ?? '',
            ...values,
            userId,
            projectDetails: this.info?.id
              ? values.projectDetailsImgList.idArr || this.info.projectDetails
              : values.projectDetailsImgList.idArr,
            trustAgreement: this.info?.id
              ? values.trustAgreementImgList.idArr || this.info.trustAgreement
              : values.trustAgreementImgList.idArr,
            projectImg: this.info?.id
              ? values.projectDetailsImgList.idArr || this.info.projectImg
              : values.projectDetailsImgList.idArr,
          }
          if (this.title === '添加新投资') {
            delete params.id
          }
          delete params.projectDetailsImgList
          delete params.trustAgreementImgList
          delete params.projectImgList
          let url = this.title === '添加新投资' ? investorsListAdd : investorsListUpdateById
          url(params).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.visible = false
              this.info = {}
              this.form.resetFields()
              this.$refs.table.refresh()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    handleCancel() {
      this.previewVisible = false
    },
  },
}
</script>
<style lang="less" scoped>
.investment_projects {
  .form {
    display: flex;
    margin-bottom: 20px;
    flex-wrap: wrap;
  }
  .permission-form {
    :deep(.permission-group) {
      margin-top: 0;
      margin-bottom: 0;
    }
  }
}
.modal {
  /deep/ .ant-modal {
    width: 800px !important;
  }

  .user_info {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    border-bottom: 1px solid #f3f4f6;
    &:last-child {
      border-bottom: none;
    }
    .item {
      display: flex;
      div {
        height: 40px;
        width: 50%;
      }
      span {
        &:first-child {
          width: 100px;
          text-align: left;
          padding: 0 15px;
        }
        &:last-child {
          text-align: left;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      .textarea {
        width: 80%;
      }
    }
  }
}
</style>
